package cn.edu.flink.tutorial.processFunction;

import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class SideOutput {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 从文件中读取数据
        String inputPath = "hello.txt";
        DataStreamSource<String> streamSource = env.readTextFile(inputPath);

        OutputTag<String> oneTag = new OutputTag<String>("one"){};

        SingleOutputStreamOperator<String> twoOutput = streamSource.process(
                new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String s, ProcessFunction<String, String>.Context context, Collector<String> collector) throws Exception {
                        if (s.contains(" ")) {
                            collector.collect(s);
                        } else {
                            context.output(oneTag, s);
                        }
                    }
                }
        );

        DataStream<String> oneOutput = twoOutput.getSideOutput(oneTag);

        oneOutput.print("one");
        twoOutput.print("two");

        env.execute();
    }
}
